package examp

import (
	"net/http"

	"fmt"

	"awfan.cn/utils"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func query(format, id string, w http.ResponseWriter, db *mgo.Database) {
	if id == "" {
		utils.WriteError(format, 404, "#id is empty", w)
		return
	}

	if !bson.IsObjectIdHex(id) {
		utils.WriteError(format, 405, fmt.Sprintf("#id is wrong format: '%v'", id), w)
		return
	}

	c := db.C(utils.PkgName(EXAMP_XML{}))

	v := EXAMP_XML{}
	q := c.FindId(bson.ObjectIdHex(id))

	var count int
	var e error
	if count, e = q.Count(); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}
	if count <= 0 {
		utils.WriteEmpty(format, w)
		return
	}

	if e = q.One(&v); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}

	utils.WriteData(format, v, w)
}
